﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using MySql.Data.MySqlClient;
using CodeRobot.Utility;
using System.Windows.Forms;

namespace CodeRobot.DAL
{
    /// <summary>
    /// .net core处理请求类
    /// </summary>
    public class ViewParentIndexHelper
    {

        /// <summary>
        /// 根据表名创建Index管理页面
        /// </summary>
        /// <param name="strFilePath">保存路径</param>
        /// <param name="strProjectName">项目名</param>
        /// <param name="strTableName">表名</param>
        public static void CreateViewIndexClass(string strFilePath,string strProjectName, string strTableName,string strTableComment, string strDBName)
        {
            //读取版权信息
            CodeRobot.Utility.IniFile iniFile = new Utility.IniFile(Application.StartupPath + "\\config.ini");
            string strCompany = iniFile.GetString("COPYRIGHT", "COMPANY", "");
            string strAuthor = iniFile.GetString("COPYRIGHT", "AUTHOR", "");
            string strVersion = iniFile.GetString("COPYRIGHT", "VERSION", "");
            string strCode = iniFile.GetString("COPYRIGHT", "CODE", "");
            string strCreateDate = iniFile.GetString("BASE", "CREATE_DATE", "");
            string strTablePrefix = iniFile.GetString("BASE", "TABLE_PREFIX", "");
            string strTableNameUpper = CommonHelper.GetTableNameUpper(strTableName);
            
            string strPrimaryKey = CommonHelper.GetPrimaryKey(strTableName);//如：news_id

            string strAllColumnName = CommonHelper.GetAllColumnName(strTableName);
            string strAllColumnNameNotKey = CommonHelper.GetAllColumnNameNotKey(strTableName);

            string strClassName = CommonHelper.GetClassName(strTableName);//类名
            strClassName = CommonHelper.GetTableNameUpper(strClassName);
            string strTableNameSpec = CommonHelper.GetTableNameFirstLowerSecondUpper(strClassName);//如：newsTypes
            string strTableNameLower = strTableNameSpec.ToLower();//如：newstypes
            string strNameValue = strPrimaryKey.Replace("_id", "");


            Directory.CreateDirectory(strFilePath);
            //为每个表创建一个独立目录存放
            string strTableNamePath = strFilePath + "\\"+ strClassName;
            if (!Directory.Exists(strTableNamePath))
            {
                Directory.CreateDirectory(strTableNamePath);
            }
            StreamWriter sw = new StreamWriter(strTableNamePath + "\\Index.cshtml", false, Encoding.GetEncoding("utf-8"));//生成物理文件
            string strTableComment2 = CommonHelper.GetColumnKeyComment(strTableComment);
            string strImgColumnName = CommonHelper.GetImgColumnName(strDBName, strTableName);
            string strSwitchColumnName = CommonHelper.GetSwitchColumnName(strDBName, strTableName);
            string strSwitchColumnNameText = CommonHelper.GetSwitchColumnNameText(strDBName, strTableName);
            string strSwitchColumnNameText2 = CommonHelper.GetSwitchColumnNameText2(strDBName, strTableName);
            string strSortColumnName = CommonHelper.GetSortColumnName(strDBName, strTableName);

            sw.WriteLine("@{");
            sw.WriteLine("    ViewData[\"Title\"] = \"" + strTableComment2 + "\";");
            sw.WriteLine("    Layout = \"~/Views/Shared/_LayoutNone.cshtml\";");
            sw.WriteLine("}");
            sw.WriteLine("<div class=\"layui-fluid\">");
            sw.WriteLine("    <div class=\"layui-card\">");
            sw.WriteLine("        <div class=\"layui-card-body\">");
            sw.WriteLine("            <div style=\"padding-bottom: 10px;\">");
            sw.WriteLine("                <button class=\"layui-btn layui-btn-sm layuiadmin-btn-list\" data-type=\"add\"><i class=\"layui-icon layui-icon-add-1\"></i>新增一级分类</button>");
            sw.WriteLine("                <span style=\"color: red\">&nbsp;&nbsp;提示：此功能仅供核心运营人员或开发人员操作使用，请谨慎操作！</span>");
            sw.WriteLine("            </div>");
            sw.WriteLine("            <table id=\"type_tree_data\" lay-filter=\"type_tree_data\"></table>");
            sw.WriteLine("            <script type=\"text/html\" id=\"table-content-list\">");
            sw.WriteLine("                <a class=\"layui-btn layui-btn-xs\" lay-event=\"add\"><i class=\"layui-icon layui-icon-add-1\"></i>新增</a>");
            sw.WriteLine("                <a class=\"layui-btn layui-btn-xs\" lay-event=\"edit\"><i class=\"layui-icon layui-icon-edit\"></i>编辑</a>");
            sw.WriteLine("                <a class=\"layui-btn layui-btn-danger layui-btn-xs\" lay-event=\"del\"><i class=\"layui-icon layui-icon-delete\"></i>删除</a>");
            sw.WriteLine("            </script>");
            sw.WriteLine("            <script type=\"text/html\" id=\"statusTpl\">");
            sw.WriteLine("                <input type=\"checkbox\" name=\"is_show\" lay-skin=\"switch\" lay-text=\"是|否\" lay-filter=\"switch_is_show\"");
            sw.WriteLine("                       value=\"{{ d." + strPrimaryKey + " }}\" data-json=\"{{ encodeURIComponent(JSON.stringify(d)) }}\" {{ d.is_show? 'checked' : '' }}>");
            sw.WriteLine("            </script>");
            //sw.WriteLine("            <input type=\"hidden\" id=\"icon_path\" name=\"icon_path\" value=\"\" />");
            //sw.WriteLine("            <input type=\"hidden\" id=\"" + strPrimaryKey + "\" name=\"" + strPrimaryKey + "\" value=\"\" />");
            //sw.WriteLine("            <input type=\"file\" id=\"btUpload\" style=\"display:none;\" />");
            sw.WriteLine("        </div>");
            sw.WriteLine("    </div>");
            sw.WriteLine("</div>");
            sw.WriteLine("");
            sw.WriteLine("<script src=\"~/layuiadmin/layui/layui.js\"></script>");
            sw.WriteLine("<script>");
            sw.WriteLine("    layui.config({");
            sw.WriteLine("        base: '/layuiadmin/' //静态资源所在路径");
            sw.WriteLine("    }).extend({");
            sw.WriteLine("        index: '/lib/index' //主入口模块");
            sw.WriteLine("    }).use(['index', 'table', 'util', 'treeTable', 'upload'], function () {");
            sw.WriteLine("        var table = layui.table");
            sw.WriteLine("            , admin = layui.admin");
            sw.WriteLine("            , form = layui.form");
            sw.WriteLine("            , upload = layui.upload");
            sw.WriteLine("            , util = layui.util;");
            sw.WriteLine("");
            sw.WriteLine("        var treeTable = layui.treeTable;");
            sw.WriteLine("        treeTable.render({");
            sw.WriteLine("            elem: '#type_tree_data',");
            sw.WriteLine("            toolbar: false,");
            sw.WriteLine("            tree: {");
            sw.WriteLine("                iconIndex: 1");
            sw.WriteLine("            },");
            sw.WriteLine("            cols: [");
            sw.WriteLine("                [");
            sw.WriteLine("                    {");
            sw.WriteLine("                        field: \"" + strPrimaryKey + "\",");
            sw.WriteLine("                        title: \"ID\",");
            sw.WriteLine("                        sort: !0,");
            sw.WriteLine("                        width: 100,");
            sw.WriteLine("                    },");
            sw.WriteLine("                    {");
            sw.WriteLine("                        field: \"type_name\",");
            sw.WriteLine("                        title: \"分类名称\",");
            sw.WriteLine("                        minWidth: 350");
            sw.WriteLine("                    },");
            sw.WriteLine("                    {");
            sw.WriteLine("                        field: \"is_show\",");
            sw.WriteLine("                        title: \"是否显示\",");
            sw.WriteLine("                        align: \"center\",");
            sw.WriteLine("                        templet: \"#statusTpl\",");
            sw.WriteLine("                        width: 120");
            sw.WriteLine("                    },");
            sw.WriteLine("                    {");
            sw.WriteLine("                        field: \"sort_num\",");
            sw.WriteLine("                        title: \"排序\",");
            sw.WriteLine("                        edit: \"text\",");
            sw.WriteLine("                        align: \"center\",");
            sw.WriteLine("                        style: \"background-color: #e8f1ff; color: #666;\",");
            sw.WriteLine("                        width: 100");
            sw.WriteLine("                    },");
            sw.WriteLine("                    {");
            sw.WriteLine("                        field: \"article_num\",");
            sw.WriteLine("                        title: \"文章数量\",");
            sw.WriteLine("                        width: 120");
            sw.WriteLine("                    },");
            sw.WriteLine("                    {");
            sw.WriteLine("                        title: \"操作\",");
            sw.WriteLine("                        width: 280,");
            sw.WriteLine("                        align: \"center\",");
            sw.WriteLine("                        fixed: \"right\",");
            sw.WriteLine("                        toolbar: \"#table-content-list\"");
            sw.WriteLine("                    }]");
            sw.WriteLine("            ],");
            sw.WriteLine("            reqData: function (data, callback) {");
            sw.WriteLine("                loading = layer.load(2, {");
            sw.WriteLine("                    shade: [0.2, '#000']");
            sw.WriteLine("                });");
            sw.WriteLine("                admin.req({");
            sw.WriteLine("                    url: '/" + strTableNameLower + "/list'");
            sw.WriteLine("                    , data: { parent_id: data ? data." + strPrimaryKey + " : \"-1\" }");
            sw.WriteLine("                    , done: function (res) {");
            sw.WriteLine("                        layer.close(loading);");
            sw.WriteLine("                        callback(res.data);");
            sw.WriteLine("                    }");
            sw.WriteLine("                });");
            sw.WriteLine("            },");
            sw.WriteLine("            style: 'margin-top:0;',");
            sw.WriteLine("        });");
            sw.WriteLine("");
            sw.WriteLine("        // 右侧操作事件");
            sw.WriteLine("        treeTable.on(\"tool(type_tree_data)\", function (t) {");
            sw.WriteLine("            var " + strPrimaryKey + " = t.data." + strPrimaryKey + ";");
            sw.WriteLine("            if (\"del\" === t.event) {");
            sw.WriteLine("                layer.confirm(\"确定删除此" + strTableComment2 + "？\", function (e) {");
            sw.WriteLine("                    admin.req({");
            sw.WriteLine("                        headers: {");
            sw.WriteLine("                            'RequestVerificationToken': csrfToken");
            sw.WriteLine("                        },");
            sw.WriteLine("                        method: 'POST',");
            sw.WriteLine("                        url: '/" + strTableNameLower + "/delete/' + " + strPrimaryKey + "");
            sw.WriteLine("                        , done: function (res) {");
            sw.WriteLine("                            t.del();");
            sw.WriteLine("                            layer.close(e);");
            sw.WriteLine("                        }");
            sw.WriteLine("                    });");
            sw.WriteLine("");
            sw.WriteLine("                });");
            sw.WriteLine("            }");
            sw.WriteLine("            else if (\"edit\" === t.event) {");
            sw.WriteLine("                layer.open({");
            sw.WriteLine("                    type: 2,");
            sw.WriteLine("                    title: \"编辑" + strTableComment2 + "\",");
            sw.WriteLine("                    content: \"/" + strTableNameLower + "/edit?id=\" + " + strPrimaryKey + ",");
            sw.WriteLine("                    maxmin: !0,");
            sw.WriteLine("                    area: [\"550px\", \"350px\"],");
            sw.WriteLine("                    btn: [\"确定\", \"取消\"],");
            sw.WriteLine("                    yes: function (e, i) {");
            sw.WriteLine("                        a = i.find(\"iframe\").contents().find(\"#layuiadmin-app-form-edit\");");
            sw.WriteLine("                        a.trigger(\"click\");");
            sw.WriteLine("                    }");
            sw.WriteLine("                })");
            sw.WriteLine("            }");
            sw.WriteLine("            else if (\"add\" === t.event) {");
            sw.WriteLine("                layer.open({");
            sw.WriteLine("                    type: 2,");
            sw.WriteLine("                    title: \"新增" + strTableComment2 + "\",");
            sw.WriteLine("                    content: \"/" + strTableNameLower + "/create?parent_id=\" + " + strPrimaryKey + ",");
            sw.WriteLine("                    maxmin: !0,");
            sw.WriteLine("                    area: [\"550px\", \"350px\"],");
            sw.WriteLine("                    btn: [\"确定\", \"取消\"],");
            sw.WriteLine("                    yes: function (e, i) {");
            sw.WriteLine("                        a = i.find(\"iframe\").contents().find(\"#layuiadmin-app-form-submit\");");
            sw.WriteLine("                        a.trigger(\"click\");");
            sw.WriteLine("                    }");
            sw.WriteLine("                })");
            sw.WriteLine("            }");
            sw.WriteLine("        }),");
            sw.WriteLine("");
            sw.WriteLine("        // 监听是否显示操作");
            sw.WriteLine("        form.on('switch(switch_is_show)', function (obj) {");
            sw.WriteLine("            var json = JSON.parse(decodeURIComponent($(this).data('json')));");
            sw.WriteLine("            var is_show = obj.elem.checked == true ? true : false;");
            sw.WriteLine("            admin.req({");
            sw.WriteLine("                headers: {");
            sw.WriteLine("                    'RequestVerificationToken': csrfToken");
            sw.WriteLine("                },");
            sw.WriteLine("                method: 'POST',");
            sw.WriteLine("                url: '/" + strTableNameLower + "/setshow?id=' + this.value + '&status=' + is_show");
            sw.WriteLine("                , done: function (res) {");
            sw.WriteLine("                    console.log(`res=${JSON.stringify(res)}`);");
            sw.WriteLine("                }");
            sw.WriteLine("            });");
            sw.WriteLine("            json = table.clearCacheKey(json);");
            sw.WriteLine("        });");
            sw.WriteLine("");
            // 处理排序字段
            if (!string.IsNullOrEmpty(strSortColumnName))
            {
                sw.WriteLine("        // 监听排序操作");
                sw.WriteLine("        treeTable.on('edit(type_tree_data)', function (obj) {");
                sw.WriteLine("            // console.log(`obj=${JSON.stringify(obj)}`);");
                sw.WriteLine("            admin.req({");
                sw.WriteLine("                headers: {");
                sw.WriteLine("                    'RequestVerificationToken': csrfToken");
                sw.WriteLine("                },");
                sw.WriteLine("                method: 'POST',");
                sw.WriteLine("                url: '/" + strTableNameLower + "/setsort?id=' + obj.data." + strPrimaryKey + " + '&sort=' + obj.value");
                sw.WriteLine("                , done: function (res) {");
                sw.WriteLine("                    // console.log(`msg=${res.msg}`);");
                sw.WriteLine("                }");
                sw.WriteLine("            });");
                sw.WriteLine("        });");
            }
            sw.WriteLine("        var $ = layui.$, active = {");
            sw.WriteLine("            add: function () {");
            sw.WriteLine("                layer.open({");
            sw.WriteLine("                    type: 2");
            sw.WriteLine("                    , title: '添加" + strTableComment2 + "'");
            sw.WriteLine("                    , content: '/" + strTableNameLower + "/create?parent_id=-1'");
            sw.WriteLine("                    , maxmin: true");
            sw.WriteLine("                    , area: ['550px', '350px']");
            sw.WriteLine("                    , btn: ['确定', '取消']");
            sw.WriteLine("                    , yes: function (index, layero) {");
            sw.WriteLine("                        var submit = layero.find('iframe').contents().find(\"#layuiadmin-app-form-submit\");");
            sw.WriteLine("                        submit.click();");
            sw.WriteLine("                    }");
            sw.WriteLine("                });");
            sw.WriteLine("            }");
            sw.WriteLine("        };");
            sw.WriteLine("");
            sw.WriteLine("        $('.layui-btn.layuiadmin-btn-list').on('click', function () {");
            sw.WriteLine("            var type = $(this).data('type');");
            sw.WriteLine("            active[type] ? active[type].call(this) : '';");
            sw.WriteLine("        });");
            sw.WriteLine("    });");
            sw.WriteLine("</script>");
            sw.Close();

        }

        /// <summary>
        /// 获取搜索字段列表
        /// </summary>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetSearchItemList(string strTableName)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释
                    

                    if (strColumnComment.Contains("{搜索}"))
                    {
                        string strColumnComment2 = CommonHelper.GetColumnKeyComment(strColumnComment);

                        string strValue = "                <div class=\"layui-inline\">\r\n";
                        strValue += "                    <label class=\"layui-form-label\">"+ strColumnComment2 + "</label>\r\n";
                        strValue += "                    <div class=\"layui-input-inline\">\r\n";
                        strValue += "                        <input type=\"text\" id=\""+ strColumnName + "\" name=\"" + strColumnName + "\" placeholder=\"请输入" + strColumnComment2 + "\" autocomplete=\"off\" class=\"layui-input\">\r\n";
                        strValue += "                    </div>\r\n";
                        strValue += "                </div>\r\n";

                        strReturnValue += strValue;
                    }

                }
                dr.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取搜索字段列表", "GetSearchItemList", false);
            }

            return strReturnValue;

        }

        /// <summary>
        /// 获取表格显示字段列表
        /// </summary>
        /// <param name="strTableName"></param>
        /// <returns></returns>
        public static string GetTableColsList(string strTableName)
        {
            string strReturnValue = "";

            try
            {
                MySqlConnection cn = new MySqlConnection(CodeRobot.DBSqlHelper.DBMySQLHelper.ConnectionMySQL());
                cn.Open();
                string strSql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_KEY,COLUMN_COMMENT,EXTRA,COLUMN_DEFAULT,CHARACTER_SET_NAME FROM `information_schema`.`COLUMNS` WHERE TABLE_NAME='" + strTableName + "' ORDER BY ordinal_position ";
                MySqlCommand cmd = new MySqlCommand(strSql, cn);
                MySqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    string strColumnName = dr["COLUMN_NAME"].ToString();//字段列名
                    string strColumnKey = dr["COLUMN_KEY"].ToString();//是否是主键
                    string strColumnComment = dr["COLUMN_COMMENT"].ToString();//注释

                    string strColumnComment2 = CommonHelper.GetColumnKeyComment(strColumnComment);

                    string strValue = "                {\r\n";
                    strValue += "                    field: \"" + strColumnName + "\",\r\n";
                    strValue += "                    title: \"" + strColumnComment2 + "\",\r\n";
                    if (strColumnName == "created_at" || strColumnKey == "PRI")
                    {
                        //主键和日期需要排序
                        strValue += "                    sort: !0,\r\n";
                    }
                    if (strColumnKey == "PRI")
                    {
                        //主键设置宽度
                        strValue += "                    width: 80,\r\n";
                    }
                    if (strColumnName == "created_at")
                    {
                        //日期设置宽度及格式
                        strValue += "                    width: 180,\r\n";
                        strValue += "                    templet: \"<div>{{layui.util.toDateString(d.created_at, 'yyyy-MM-dd HH:mm')}}</div>\",\r\n";
                    }
                    strValue += "                },\r\n";

                    strReturnValue += strValue;

                }
                dr.Dispose();
                cn.Close();
            }
            catch (Exception ex)
            {
                CodeRobot.Utility.LogHelper.Error(typeof(CodeHelper), ex, "获取搜索字段列表", "GetSearchItemList", false);
            }

            return strReturnValue;

        }



    }
}
